package com.sanery.ui.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sanery.entity.User;
import com.sanery.service.UserService;
import com.sanery.service.impl.UserServiceImpl;

@Controller
public class UserController {
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			return "redirect:/index";
		}
		return "/login";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String login(@RequestParam(required = true) String username, @RequestParam(required = true) String password,
			HttpSession session) { // @RequestParam(required=true) 表示必须要有
		// 数据库查询 user
		UserService service = new UserServiceImpl();
		User user = service.getUser(username, password);
		int canlogin = 0;
		String json = "";
		if (user != null) {
			session.setAttribute("user", user);
			canlogin = 1;
		}
		json = "{\"msg\":" + canlogin + "}";
		return json;
	}

	@RequestMapping(value = "/reg", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String reg(@RequestParam(required = true) String username, @RequestParam(required = true) String password,
			@RequestParam(required = true) String email) {
		String json = "";
		UserService service = new UserServiceImpl();
		Integer num = service.addUser(username, password, email);
		json = "{\"msg\":" + num + "}";
		return json;
	}
}
